﻿Imports System.Xml
Imports System.Net
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Security.Cryptography.X509Certificates
Imports MSXML2
Imports Microsoft.Exchange.WebServices
Imports Microsoft.Exchange.WebServices.Autodiscover
Imports Microsoft.Exchange.WebServices.Data

Public Class ModifyOutLook

    'Public cs_id As Integer

    Public Sub New()
    End Sub

    Public Sub New(ByVal cs_id_construct, ByVal username_construct, ByVal pwd_construct, ByVal domain_construct, ByVal appt_file_construct, ByVal subject_text_construct, ByVal server_construct, ByVal reminder_construct)
        Me.cs_id = cs_id_construct
        Me.username = username_construct
        Me.pwd = pwd_construct
        Me.domain = domain_construct
        Me.appt_file = appt_file_construct
        Me.subject_text = subject_text_construct
        Me.server = server_construct
        Me.reminder = reminder_construct
    End Sub

    Public Sub New(ByVal folder_construct, ByVal username_construct, ByVal pwd_construct, ByVal domain_construct, ByVal contact_file_construct, ByVal server_construct, ByVal reminder_construct)
        Me.folder = folder_construct
        Me.username = username_construct
        Me.pwd = pwd_construct
        Me.domain = domain_construct
        Me.contact_file = contact_file_construct
        Me.server = server_construct
        Me.reminder = reminder_construct
    End Sub

    Private reminder_val As String
    Public Property reminder() As String
        Get
            Return reminder_val
        End Get
        Set(ByVal value As String)
            reminder_val = value
        End Set
    End Property

    Private username_val As String
    Public Property username() As String
        Get
            Return username_val
        End Get
        Set(ByVal value As String)
            username_val = value
        End Set
    End Property

    Private pwd_val As String
    Public Property pwd() As String
        Get
            Return pwd_val
        End Get
        Set(ByVal value As String)
            pwd_val = value
        End Set
    End Property

    Private domain_val As String
    Public Property domain() As String
        Get
            Return domain_val
        End Get
        Set(ByVal value As String)
            domain_val = value
        End Set
    End Property

    Private appt_file_val As String
    Public Property appt_file() As String
        Get
            Return appt_file_val
        End Get
        Set(ByVal value As String)
            appt_file_val = value
        End Set
    End Property

    Private contact_file_val As String
    Public Property contact_file() As String
        Get
            Return contact_file_val
        End Get
        Set(ByVal value As String)
            contact_file_val = value
        End Set
    End Property

    Private server_val As String
    Public Property server() As String
        Get
            Return server_val
        End Get
        Set(ByVal value As String)
            server_val = value
        End Set
    End Property

    Private subject_text_val As String
    Public Property subject_text() As String
        Get
            Return subject_text_val
        End Get
        Set(ByVal value As String)
            subject_text_val = value
        End Set
    End Property

    
    Private cs_id_val As String
    Public Property cs_id() As String
        Get
            Return cs_id_val
        End Get
        Set(ByVal value As String)
            cs_id_val = value
        End Set
    End Property

    Private folder_val As String
    Public Property folder() As String
        Get
            Return folder_val
        End Get
        Set(ByVal value As String)
            folder_val = value
        End Set
    End Property

    Public Sub BuildOutlookAppts()
        Try
            Dim m_xmld As System.Xml.XmlDocument
            Dim m_nodelist As XmlNodeList
            'Dim m_node As XmlNode
            'Create the XML Document
            m_xmld = New System.Xml.XmlDocument()
            'Load the Xml file
            m_xmld.Load(appt_file)
            'Get the list of name nodes 
            m_nodelist = m_xmld.SelectNodes("/appointments/appt")
            'Loop through the nodes
            For Each m_node In m_nodelist
                Dim CS_ID_Appt = m_node.Item("cs_id").InnerXml
                Dim Appt_ID = m_node.Item("appt_id").InnerXml
                Dim Subject = m_node.Item("subject").InnerXml
                Dim Location = m_node.Item("location").InnerXml
                Dim Body = m_node.Item("body").InnerXml
                Dim Start_Date = m_node.Item("start").InnerXml
                Dim End_Date = m_node.Item("end").InnerXml

                If (cs_id = CS_ID_Appt) And (Convert.ToDateTime(Start_Date) > Now) Then
                    Console.WriteLine("Writing Appointment ID: " & Appt_ID & " for Cornerstone User: " & cs_id)

                    Call CreateOutlookApptEWS(Appt_ID, Subject, Location, Body, Start_Date, End_Date, username, domain, pwd, server, subject_text, reminder)

                    Console.WriteLine("Wrote Appointment ID: " & Appt_ID & " for Cornerstone User: " & cs_id)
                Else
                    Console.WriteLine("Appointment ID: " & Appt_ID & " not associated with Cornerstone User: " & cs_id)
                End If
                Console.Write(vbCrLf)
            Next
        Catch errorVariable As Exception
            'Error trapping
            Console.Write(errorVariable.ToString())
        End Try

    End Sub

    Private Sub CreateOutlookApptEWS(ByVal Appt_ID As String, ByVal Subject As String, ByVal Location As String, ByVal Body As String, ByVal Start_Date As Object, ByVal End_Date As Object, ByVal username As String, ByVal domain As String, ByVal pwd As String, ByVal server As String, ByVal subject_text As String, ByVal reminder As String)

        Try
            Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2007_SP1)

            exch.Url = New System.Uri("https://" & server & "/EWS/Exchange.asmx")
            exch.UseDefaultCredentials = True

            exch.Credentials = New System.Net.NetworkCredential(username, pwd, domain)

            Dim appt As Appointment = New Appointment(exch)

            appt.Subject = "Cornerstone Appt (" & Appt_ID & ") : " & Subject
            appt.Body = Body
            appt.Start = Start_Date

            appt.End = End_Date

            appt.IsAllDayEvent = False
            appt.LegacyFreeBusyStatus = LegacyFreeBusyStatus.OOF
            appt.IsReminderSet = False

            appt.Save(WellKnownFolderName.Calendar, SendInvitationsMode.SendToNone)

            appt = Nothing
            exch = Nothing

        Catch ex As Exception

            Console.WriteLine(ex.Message)

        End Try

    End Sub


    Public Sub FindAndDeleteOutlookAppt()

        Try

            Dim resp = FindOutlookApptEWS()


            If resp.Equals(Nothing) Then
                Console.WriteLine("No Appointments")
                Return
            End If

            For i As Integer = 0 To resp.Items.Count - 1

             
                Dim appointment As Appointment = DirectCast(resp.Items(i), Appointment)

                'Console.WriteLine("Subject = " & appointment.Subject)
                'Console.WriteLine("StartTime = " & appointment.Start)
                'Console.WriteLine("EndTime = " & appointment.End)
                'Console.WriteLine("Unique ID = " & appointment.ICalUid)
                'Console.WriteLine("----------------------------------------------------------------")

                Dim open_paren_val = InStr(appointment.Subject, "(")
                Dim close_paren_val = InStr(appointment.Subject, ")")

                Dim num_chars = close_paren_val - open_paren_val

                If (num_chars > 0) Then

                    Dim Appt_Subject_ID = appointment.Subject.Substring(open_paren_val, num_chars - 1)
                    Console.WriteLine("Deleting Appt ID: " & Appt_Subject_ID)
                    DeleteOutlookApptEWS(appointment)
                Else
                    Console.WriteLine("Appt ID not found, skipping...")
                End If

            Next

        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

    End Sub

    Private Function FindOutlookApptEWS() As Microsoft.Exchange.WebServices.Data.FindItemsResults(Of Microsoft.Exchange.WebServices.Data.Appointment)

        Try

            Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2007_SP1)

            exch.Url = New System.Uri("https://" & server & "/EWS/Exchange.asmx")
            exch.UseDefaultCredentials = True

            exch.Credentials = New System.Net.NetworkCredential(username, pwd, domain)

            Dim startDate As Date = Date.Today.AddDays(-10)

            Dim endDate As Date = Date.Today.AddDays(30)


            Dim cView As CalendarView = New CalendarView(startDate, endDate)

            Dim calendar As CalendarFolder = CalendarFolder.Bind(exch, WellKnownFolderName.Calendar)

            Dim response = calendar.FindAppointments(cView)

            exch = Nothing
            cView = Nothing

            Return response

        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

        Return Nothing

    End Function


    Private Sub DeleteOutlookApptEWS(ByVal appt As Appointment)

        Try

            Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2007_SP1)

            exch.Url = New System.Uri("https://" & server & "/EWS/Exchange.asmx")
            exch.UseDefaultCredentials = True

            exch.Credentials = New System.Net.NetworkCredential(username, pwd, domain)

            appt.Delete(DeleteMode.HardDelete)


            exch = Nothing


        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

    End Sub


    Public Sub BuildOutlookContactEWS()
        Try
            Dim m_xmld As System.Xml.XmlDocument
            Dim m_nodelist As XmlNodeList
            Dim m_node As XmlNode

            Dim id As FolderId = Nothing

            Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2007_SP1)

            exch.Url = New System.Uri("https://" & server & "/EWS/Exchange.asmx")
            exch.UseDefaultCredentials = True

            exch.Credentials = New System.Net.NetworkCredential(username, pwd, domain)

            Dim publicFolderRoot As FindFoldersResults = exch.FindFolders(WellKnownFolderName.PublicFoldersRoot, New FolderView(10))

            For Each FLD As Folder In publicFolderRoot

                If FLD.DisplayName = folder Then
                    id = FLD.Id
                End If

            Next

            If (id Is Nothing) Then
                Console.WriteLine("Could not find public folder " & folder & ". Exitting....")
                Return

            End If

            'Create the XML Document
            m_xmld = New System.Xml.XmlDocument()
            'Load the Xml file
            m_xmld.Load(contact_file)
            'Get the list of name nodes 
            m_nodelist = m_xmld.SelectNodes("/contacts/contact")
            'Loop through the nodes
            For Each m_node In m_nodelist
                Dim contact_id = m_node.Item("contact_id").InnerXml
                Dim full_name = m_node.Item("full_name").InnerXml
                Dim other_phone = m_node.Item("other_phone").InnerXml
                Dim other_street = m_node.Item("other_street").InnerXml
                Dim other_street2 = m_node.Item("other_street2").InnerXml
                Dim other_city = m_node.Item("other_city").InnerXml
                Dim other_state = m_node.Item("other_state").InnerXml
                Dim other_zip = m_node.Item("other_zip").InnerXml
                Dim email = m_node.Item("other_email").InnerXml
                ' Dim fileasname = m_node.Item("fileasname").InnerXml
                'Dim firstname = m_node.Item("firstname").InnerXml
                'Dim lastname = m_node.Item("lastname").InnerXml

                Dim contact As Contact = New Contact(exch)

                contact.DisplayName = full_name

                Dim paEntry1 As PhysicalAddressEntry = New PhysicalAddressEntry()
                paEntry1.Street = other_street

                paEntry1.City = other_city

                paEntry1.State = other_state

                paEntry1.PostalCode = other_zip

                paEntry1.CountryOrRegion = "United States"

                contact.PhysicalAddresses(PhysicalAddressKey.Other) = paEntry1

                If (other_phone Is Nothing Or other_phone.Length <= 0) Then
                Else
                    contact.PhoneNumbers(PhoneNumberKey.OtherTelephone) = other_phone
                End If

                If (email Is Nothing Or email.Length <= 0) Then
                Else
                    contact.EmailAddresses(EmailAddressKey.EmailAddress1) = email
                End If

                contact.Department = contact_id

                contact.FileAs = full_name

                contact.Save(id)

                Console.WriteLine("Writing Cornerstone Contact id: " & contact_id & " for Cornerstone Name: " & full_name)
            Next

            exch = Nothing

        Catch errorVariable As Exception
            'Error trapping
            Console.Write(errorVariable.ToString())
        End Try

    End Sub


    Public Sub FindAndDeleteOutlookContactsEWS()
        Try

            Dim numTrys As Integer = 10

            Dim id As FolderId = Nothing

            Dim exch As ExchangeService = New ExchangeService(ExchangeVersion.Exchange2007_SP1)

            exch.Url = New System.Uri("https://" & server & "/EWS/Exchange.asmx")
            exch.UseDefaultCredentials = True

            exch.Credentials = New System.Net.NetworkCredential(username, pwd, domain)

            Dim publicFolderRoot As FindFoldersResults = exch.FindFolders(WellKnownFolderName.PublicFoldersRoot, New FolderView(10))

            For Each FLD As Folder In publicFolderRoot

                If FLD.DisplayName = folder Then
                    id = FLD.Id
                End If

            Next

            If (id Is Nothing) Then
                Console.WriteLine("Could not find public folder " & folder & ". Exitting....")
                Return

            End If

            Dim contactFld As ContactsFolder = ContactsFolder.Bind(exch, id)

            If (contactFld.TotalCount < 1) Then
                Console.WriteLine("No Contacts were found in folder: " & folder)
                Return
            End If

            Console.WriteLine("Total Number of Contacts: " & contactFld.TotalCount)

            REM Console.WriteLine("Empty Contacts Folder... ")
            REM contactFld.Empty(DeleteMode.HardDelete, True)

            Dim view As ItemView = New ItemView(contactFld.TotalCount)



START_AGAIN:

            Dim count As Integer

            count = 0

            Dim f As FindItemsResults(Of Item) = contactFld.FindItems(view)

            Console.WriteLine("Total Number of Contacts1: " & f.TotalCount)

            For Each i As Item In f

                Dim con As Contact = i

                Console.WriteLine("Deleting Contact: " & con.Department)

                con.Delete(DeleteMode.HardDelete)

                count = count + 1
            Next

            Console.WriteLine("Total Number deleted: " & count)

            If (count < f.TotalCount And numTrys > 0) Then
                numTrys = numTrys - 1

                GoTo START_AGAIN

            End If


            exch = Nothing

        Catch errorVariable As Exception
            'Error trapping
            Console.Write(errorVariable.ToString())
        End Try

    End Sub

    Public Sub FindAndDeleteOutlookContacts()

        ' Variables
        Dim strContactUri As String
        Dim strApptRequest As String
        Dim ResponseXmlDoc As System.Xml.XmlDocument
        Dim SubjectNodeList As System.Xml.XmlNodeList
        Dim xmldom As DOMDocument
        Try

            ' URI of the user's calendar folder.
            strContactUri = "https://" & server & "/public/" & folder & "/"

            Console.WriteLine(strContactUri)

            strApptRequest = "<?xml version=""1.0""?>" & _
                 "<g:searchrequest xmlns:g=""DAV:"">" & _
                 "<g:sql>SELECT ""urn:schemas:contacts:o""" & _
                 "FROM Scope('SHALLOW TRAVERSAL OF """ & strContactUri & """') " & _
                 "</g:sql></g:searchrequest>"

            xmldom = SendWebDavRequest("SEARCH", strContactUri, strApptRequest, domain, username, pwd)
            ResponseXmlDoc = New System.Xml.XmlDocument
            ResponseXmlDoc.LoadXml(xmldom.xml)

            'Console.WriteLine(ResponseXmlDoc.InnerXml())
            ' Build a list of the urn:schemas:httpmail:subject XML nodes,
            ' corresponding to the calendar item subjects returned in the search request.
            ' The urn:schemas:httpmail: namespace is typically
            ' assigned the e: prefix in the XML response body.
            SubjectNodeList = ResponseXmlDoc.GetElementsByTagName("d:o")

            ' Loop through the returned items (if any).
            If SubjectNodeList.Count > 0 Then

                Console.WriteLine("Contacts Company Returned a Total of: " & SubjectNodeList.Count - 1)

                Dim i As Integer
                For i = 0 To SubjectNodeList.Count - 1

                    ' Display the subject.
                    Console.WriteLine(" Deleting contact with the company:       " + SubjectNodeList(i).InnerText)
                    Dim company = SubjectNodeList(i).InnerText

                    Dim colon_val = InStr(company, ":")
                    'Dim string_length = company.Length()
                    'Console.WriteLine("Colon Val" & colon_val + 1)
                    'Console.WriteLine("String Length" & string_length)
                    'Dim num_chars = close_paren_val - open_paren_val

                    Dim del_contact_id = company.Substring(colon_val + 1)

                    'Console.WriteLine("Contact Company:|" & company & "|")

                    DeleteOutlookContactOWA(del_contact_id, username, pwd, domain, contact_file, server)
                Next

            Else
                Console.WriteLine("No contacts found ...")

            End If

            ' Clean up.
            ResponseXmlDoc = Nothing
            xmldom = Nothing

        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

    End Sub


    Public Sub BuildOutlookContact()
        Try
            Dim m_xmld As System.Xml.XmlDocument
            Dim m_nodelist As XmlNodeList
            Dim m_node As XmlNode
            'Create the XML Document
            m_xmld = New System.Xml.XmlDocument()
            'Load the Xml file
            m_xmld.Load(contact_file)
            Console.WriteLine("here loading file")

            'Get the list of name nodes 
            m_nodelist = m_xmld.SelectNodes("/contacts/contact")
            'Loop through the nodes
            For Each m_node In m_nodelist

                Console.WriteLine("here looking at list")

                Dim contact_id = m_node.Item("contact_id").InnerXml
                Dim full_name = m_node.Item("full_name").InnerXml
                Dim other_phone = m_node.Item("other_phone").InnerXml
                Dim other_street = m_node.Item("other_street").InnerXml
                Dim other_street2 = m_node.Item("other_street2").InnerXml
                Dim other_city = m_node.Item("other_city").InnerXml
                Dim other_state = m_node.Item("other_state").InnerXml
                Dim other_zip = m_node.Item("other_zip").InnerXml
                Dim email = m_node.Item("other_email").InnerXml
                Dim fileasname = m_node.Item("fileasname").InnerXml
                Dim firstname = m_node.Item("firstname").InnerXml
                Dim lastname = m_node.Item("lastname").InnerXml

                Console.WriteLine("here")

                Call CreateOutlookContactOWA(contact_id, full_name, fileasname, other_phone, other_street, other_street2, other_city, other_state, other_zip, email, folder, domain, username, pwd, server, firstname, lastname)


                Console.Write("Writing Cornerstone Contact id: " & contact_id & " for Cornerstone Name: " & full_name)
            Next
        Catch errorVariable As Exception
            'Error trapping
            Console.Write(errorVariable.ToString())
        End Try

    End Sub


    Private Sub DeleteOutlookApptOWA(ByVal cs_id, ByVal username, ByVal pwd, ByVal domain, ByVal appt_file, ByVal server, ByVal Appt_Subject_ID)

        Dim strCalendarUri As String
        Dim strApptItem As String

        Try

            ' Appointment item.
            strApptItem = "CornerStoneAppt_" & Appt_Subject_ID & ".eml"

            ' URI of the user's calendar folder.
            strCalendarUri = "https://" & server & "/exchange/" & username & "/Calendar/"

            SendWebDavRequest("DELETE", strCalendarUri & strApptItem, Nothing, domain, username, pwd)

            strCalendarUri = Nothing
            strApptItem = Nothing

        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

    End Sub


    Private Sub CreateOutlookContactOWA(ByVal contact_id, ByVal full_name, ByVal fileasname, ByVal other_phone, ByVal other_street, ByVal other_street2, ByVal other_city, ByVal other_state, ByVal other_zip, ByVal email, ByVal folder, ByVal domain, ByVal username, ByVal pwd, ByVal server, ByVal firstname, ByVal lastname)

        ' Variables
        Dim strCalendarUri As String
        Dim strApptItem As String
        Dim strXMLNSInfo As String
        Dim strOtherAddrInfo As String
        Dim strPhoneInfo As String
        Dim strEmailInfo As String
        Dim strNameInfo As String
        Dim strOrganizationalInfo As String
        Dim strBody As String

        Try

            ' Appointment item.
            strApptItem = "Contact_" & contact_id & ".eml"

            ' URI of the user's calendar folder.
            strCalendarUri = "https://" & server & "/public/" & folder & "/"

            strXMLNSInfo = "xmlns:g=""DAV:"" " & _
        "xmlns:c=""urn:schemas:contacts:"" " & _
        "xmlns:e=""http://schemas.microsoft.com/exchange/"" " & _
        "xmlns:mapi=""http://schemas.microsoft.com/mapi/"" " & _
        "xmlns:x=""xml:"" xmlns:cal=""urn:schemas:calendar:"" " & _
        "xmlns:mail=""urn:schemas:httpmail:"">"
            ' Specify the Other Address Information.
            ' (Street, PO Box, City, State, Postal Code, and Country)
            strOrganizationalInfo = "<c:o>CStone ID: " & contact_id & "</c:o>"

            strNameInfo = "<c:givenName>" & firstname & "</c:givenName>" & _
             "<c:sn>" & lastname & "</c:sn>" & _
            "<c:cn>" & full_name & "</c:cn>" & _
            "<mail:subject>" & firstname & " " & lastname & "</mail:subject>"


            strOtherAddrInfo = "<c:otherstreet>" & other_street & "</c:otherstreet>" & _
                "<c:otherpostofficebox>" & other_street2 & "</c:otherpostofficebox>" & _
                "<c:othercity>" & other_city & "</c:othercity>" & _
                "<c:otherstate>" & other_state & "</c:otherstate>" & _
                "<c:otherpostalcode>" & other_zip & "</c:otherpostalcode>" & _
                "<c:fileas>" & fileasname & "</c:fileas>" & _
                "<c:othercountry>US</c:othercountry>"

            strPhoneInfo = "<c:homePhone>" & other_phone & "</c:homePhone>"

            strEmailInfo = "<mapi:emaillisttype>1</mapi:emaillisttype>" & _
"<mapi:email1addrtype>SMTP</mapi:email1addrtype>" & _
"<mapi:email1originaldisplayname>" & full_name & "</mapi:email1originaldisplayname>" & _
"<mapi:email1emailaddress>" & email & "</mapi:email1emailaddress>"

            ' Put all the information together in an HTTP request.
            strBody = "<?xml version=""1.0""?>" & _
                "<g:propertyupdate " & strXMLNSInfo & _
                    "<g:set>" & _
                        "<g:prop>" & _
                            "<g:contentclass>urn:content-classes:person</g:contentclass>" & _
                            "<e:outlookmessageclass>IPM.Contact</e:outlookmessageclass>" & _
                            strOrganizationalInfo & _
                            strNameInfo & _
                            strOtherAddrInfo & _
                            strPhoneInfo & _
                            strEmailInfo & _
                        "</g:prop>" & _
                    "</g:set>" & _
                "</g:propertyupdate>"

            SendWebDavRequest("PROPPATCH", strCalendarUri & strApptItem, strBody, domain, username, pwd)
            Console.WriteLine("Contact successfully created.")

        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

    End Sub

    Private Sub DeleteOutlookContactOWA(ByVal del_contact_id, ByVal username, ByVal pwd, ByVal domain, ByVal contact_file, ByVal server)

        Dim strContactUri As String
        Dim strContItem As String

        Try
            ' Appointment item.
            strContItem = "Contact_" & del_contact_id & ".eml"

            ' URI of the user's calendar folder.
            strContactUri = "https://" & server & "/public/" & folder & "/"

            SendWebDavRequest("DELETE", strContactUri & strContItem, Nothing, domain, username, pwd)

            Console.WriteLine("   Delete of Contact ID: " & del_contact_id & " successful. ")

            strContactUri = Nothing
            strContItem = Nothing

        Catch ex As Exception
            ' Catch any exceptions. Any error codes from the PROPPATCH
            ' or MOVE method requests on the server will be caught
            ' here, also.
            Console.WriteLine(ex.Message)

        End Try

    End Sub


    Private Function SendWebDavRequest(ByVal oper As String, ByVal url As String, ByVal rqst As String, ByVal strDomain As String, ByVal strUserName As String, ByVal strPassword As String) As DOMDocument

        Dim xmlReq As MSXML2.XMLHTTP40
        Dim xmldom As DOMDocument

        ' Create the DAV PROPPATCH request.
        xmlReq = CreateObject("Microsoft.XMLHTTP")

        Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateCertificate

        Console.WriteLine(url & " " & strDomain & " " & strUserName & " " & strPassword)

        xmlReq.open(oper, url, False, strDomain & "\" & strUserName, strPassword)

        If (oper = "DELETE") Then
            xmlReq.send()
        Else
            xmlReq.setRequestHeader("Content-Type", "text/xml")
            xmlReq.send(rqst)
        End If


        ' The PROPPATCH request was successful.
        If (xmlReq.status >= 200 And xmlReq.status < 300) Then
            Console.WriteLine("operation completed successfully.")
        Else
            Console.WriteLine("status: " & xmlReq.status & vbCrLf & "Status text: " & xmlReq.statusText & vbCrLf & " Response: " & xmlReq.responseText)
        End If

        '        ' Create the XmlDocument object from the XML response stream.
        ' ResponseXmlDoc = New System.Xml.XmlDocument

        xmldom = xmlReq.responseXML

        '   ResponseXmlDoc.LoadXml(xmldom.xml)

        ' Clean up.
        xmlReq = Nothing

        Return xmldom

    End Function


    Private Function ValidateCertificate(ByVal sender As Object, ByVal certificate As X509Certificate, ByVal chain As X509Chain, ByVal sslPolicyErrors As Net.Security.SslPolicyErrors) As Boolean
        Dim validationResult As Boolean
        validationResult = True
        '
        ' policy code here ...
        '
        Return validationResult
    End Function

    Private Function AuthenticateSecureOWA(ByVal strServerName As String, ByVal strDomain As String, ByVal strUserName As String, ByVal strPassword As String) As String
        Dim AuthURL As System.Uri
        Dim Cookiejar As CookieContainer
        Dim strCookies As String
        Try
            ' Construct our destination URI.
            AuthURL = New System.Uri("https://" + strServerName + "/owa/auth/owaauth.dll")
        Catch ex As Exception
            Console.WriteLine("Error occurred while you are creating the URI for OWA authentication!" + vbCrLf + vbCrLf + ex.Message)
            Return "Error"
        End Try

        Dim WebReq As HttpWebRequest
        Cookiejar = New CookieContainer

        ' Create our request object for the constructed URI.
        WebReq = CType(WebRequest.Create(AuthURL), HttpWebRequest)
        WebReq.CookieContainer = Cookiejar

        ' Create our post data string that is required by OWA (owaauth.dll).
        ' EEH modified owa in line below from exchange
        Dim strPostFields As String = "destination=https%3A%2F%2F" & strServerName & "%2Fexchange%2F" + strUserName + "%2F&username=" + strDomain + "%5C" + strUserName + "&password=" + strPassword + "&SubmitCreds=Log+On&forcedownlevel=0&trusted=0"

        WebReq.KeepAlive = True
        WebReq.AllowAutoRedirect = False
        WebReq.Method = "POST"

        ' Store the post data into a byte array.
        Dim PostData() As Byte = System.Text.Encoding.ASCII.GetBytes(strPostFields)

        ' Set the content length.
        WebReq.ContentLength = PostData.Length

        Dim tmpStream As Stream

        Try
            ' Create a request stream. Write the post data to the stream.
            tmpStream = WebReq.GetRequestStream()
            tmpStream.Write(PostData, 0, PostData.Length)
            tmpStream.Close()
        Catch ex As Exception
            Console.WriteLine("Error occurred while trying OWA authentication!" + vbCrLf + vbCrLf + ex.Message)
            Return "Error"
        End Try

        ' Get the response from the request.
        Dim WebResp As HttpWebResponse = WebReq.GetResponse()

        ' Create a stream to capture the response data
        Dim tmpStreamRead As New StreamReader(WebResp.GetResponseStream())

        ' Write returned data to a string.
        Dim strResponseData As String = tmpStreamRead.ReadToEnd()
        tmpStreamRead.Close()

        ' Close the response object.
        WebResp.Close()

        ' Get our returned cookie set.
        strCookies = Cookiejar.GetCookieHeader(AuthURL).ToString()

        ' Filter for our cadata and session ID cookies.
        Dim strCADataCookie As String = Regex.Replace(strCookies, "(.*)cadata=""(.*)""(.*)", "$2")
        Dim strSessionIDCookie As String = Regex.Replace(strCookies, "(.*)sessionid=(.*)(,|;)(.*)", "$2")

        ' Create and return the cookie set for performing subsequent Web requests.
        strCookies = "sessionid=" + strSessionIDCookie + "; " + "cadata=" + strCADataCookie
        Return strCookies
    End Function

    'Public Sub FindAndDeleteOutlookApptOWA(ByVal cs_id, ByVal username, ByVal pwd, ByVal domain, ByVal appt_file, ByVal server, ByVal subject)

    '    ' Variables
    '    Dim strExchSvrName As String
    '    Dim strMailbox As String
    '    Dim strCalendarUri As String
    '    Dim strApptItem As String
    '    Dim strDomain As String
    '    Dim strUserName As String
    '    Dim strPassword As String
    '    Dim strApptRequest As String
    '    Dim strMailInfo As String
    '    Dim strCalInfo As String
    '    Dim strXMLNSInfo As String
    '    Dim strHeaderInfo As String
    '    Dim PROPPATCHRequest As System.Net.HttpWebRequest
    '    Dim PROPPATCHResponse As System.Net.WebResponse
    '    Dim bytes() As Byte
    '    Dim PROPPATCHRequestStream As System.IO.Stream

    '    Dim Request As System.Net.HttpWebRequest
    '    Dim Response As System.Net.HttpWebResponse
    '    Dim MyCredentialCache As System.Net.CredentialCache

    '    Dim strQuery As String

    '    Dim RequestStream As System.IO.Stream
    '    Dim ResponseStream As System.IO.Stream
    '    Dim ResponseXmlDoc As System.Xml.XmlDocument
    '    Dim HrefNodes As System.Xml.XmlNodeList
    '    Dim SizeNodes As System.Xml.XmlNodeList
    '    Dim SubjectNodeList As System.Xml.XmlNodeList
    '    Dim LocationNodeList As System.Xml.XmlNodeList
    '    Dim StartTimeNodeList As System.Xml.XmlNodeList
    '    Dim EndTimeNodeList As System.Xml.XmlNodeList
    '    Dim BusyStatusNodeList As System.Xml.XmlNodeList
    '    Dim InstanceTypeNodeList As System.Xml.XmlNodeList

    '    Try
    '        'ServicePointManager.ServerCertificateValidationCal lback = delegate { return true; };
    '        ' Exchange server name
    '        strExchSvrName = server

    '        ' Mailbox folder name.
    '        strMailbox = username

    '        ' Appointment item.
    '        'strApptItem = "CornerStoneAppt_" & Appt_ID & ".eml"

    '        ' URI of the user's calendar folder.


    '        strCalendarUri = "https://" & strExchSvrName & "/owa/" & _
    '        strMailbox & "/Calendar/"



    '        ' User name and password of appointment creator.
    '        strUserName = username
    '        strDomain = domain
    '        strPassword = pwd

    '        Console.WriteLine(strCalendarUri)

    '        ' Build the XML body of the PROPPATCH request.
    '        strApptRequest = "<?xml version=""1.0""?>" & _
    '             "<g:searchrequest xmlns:g=""DAV:"">" & _
    '             "<g:sql>SELECT ""urn:schemas:calendar:location"", ""urn:schemas:httpmail:subject"", " & _
    '             """urn:schemas:calendar:dtstart"", ""urn:schemas:calendar:dtend"", " & _
    '             """urn:schemas:calendar:busystatus"", ""urn:schemas:calendar:instancetype"" " & _
    '             "FROM Scope('SHALLOW TRAVERSAL OF """ & strCalendarUri & """') " & _
    '             "WHERE NOT ""urn:schemas:calendar:instancetype"" = 1 " & _
    '             "AND ""urn:schemas:httpmail:subject"" LIKE '" & subject & "' " & _
    '             "AND ""DAV:contentclass"" = 'urn:content-classes:appointment' " & _
    '             "AND ""urn:schemas:calendar:dtstart"" > '2009/06/01 00:00:00' " & _
    '             "ORDER BY ""urn:schemas:calendar:dtstart"" ASC" & _
    '             "</g:sql></g:searchrequest>"

    '        Dim strReusableCookies As String
    '        Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateCertificate
    '        PROPPATCHRequest = CType(WebRequest.Create(New System.Uri(strCalendarUri)), HttpWebRequest)

    '        strReusableCookies = AuthenticateSecureOWA(strExchSvrName, strDomain, strUserName, strPassword)

    '        PROPPATCHRequest.Headers.Add("Cookie", strReusableCookies)

    '        ' Specify the PROPPATCH method.
    '        PROPPATCHRequest.Method = "SEARCH"

    '        ' Set the content type header.
    '        PROPPATCHRequest.ContentType = "text/xml"

    '        PROPPATCHRequest.KeepAlive = True
    '        PROPPATCHRequest.AllowAutoRedirect = False

    '        ' Encode the body using UTF-8.
    '        bytes = System.Text.Encoding.UTF8.GetBytes(strApptRequest)

    '        ' Set the content header length.  This must be
    '        ' done before writing data to the request stream.
    '        PROPPATCHRequest.ContentLength = bytes.Length

    '        ' Get a reference to the request stream.
    '        PROPPATCHRequestStream = PROPPATCHRequest.GetRequestStream()

    '        ' Write the message body to the request stream.
    '        PROPPATCHRequestStream.Write(bytes, 0, bytes.Length)

    '        ' Close the Stream object to release the connection
    '        ' for further use.
    '        PROPPATCHRequestStream.Close()

    '        ' Create the appointment in the Calendar folder of the
    '        ' user's mailbox.
    '        PROPPATCHResponse = CType(PROPPATCHRequest.GetResponse(), System.Net.HttpWebResponse)

    '        ResponseStream = PROPPATCHResponse.GetResponseStream()

    '        ' Create the XmlDocument object from the XML response stream.
    '        ResponseXmlDoc = New System.Xml.XmlDocument
    '        ResponseXmlDoc.Load(ResponseStream)

    '        ' Build a list of the urn:schemas:httpmail:subject XML nodes,
    '        ' corresponding to the calendar item subjects returned in the search request.
    '        ' The urn:schemas:httpmail: namespace is typically
    '        ' assigned the e: prefix in the XML response body.
    '        SubjectNodeList = ResponseXmlDoc.GetElementsByTagName("e:subject")

    '        ' Loop through the returned items (if any).
    '        If SubjectNodeList.Count > 0 Then

    '            Console.WriteLine("Calendar items...")
    '            Dim str As String
    '            Dim i As Integer
    '            For i = 0 To SubjectNodeList.Count - 1

    '                ' Display the subject.
    '                Console.WriteLine(" Deleting appointment with the subject:       " + SubjectNodeList(i).InnerText)
    '                Dim Appt_Subject = SubjectNodeList(i).InnerText

    '                Dim open_paren_val = InStr(Appt_Subject, "(")
    '                Dim close_paren_val = InStr(Appt_Subject, ")")

    '                Dim num_chars = close_paren_val - open_paren_val

    '                Dim Appt_Subject_ID = Appt_Subject.Substring(open_paren_val, num_chars - 1)

    '                Console.WriteLine("Appt ID: " & Appt_Subject_ID)

    '                DeleteOutlookApptOWA(cs_id, username, pwd, domain, appt_file, server, Appt_Subject_ID)
    '            Next

    '        Else
    '            Console.WriteLine("No calendar items found ...")

    '        End If

    '        ' Clean up.
    '        ResponseStream.Close()
    '        PROPPATCHResponse.Close()

    '    Catch ex As Exception
    '        ' Catch any exceptions. Any error codes from the PROPPATCH
    '        ' or MOVE method requests on the server will be caught
    '        ' here, also.
    '        Console.WriteLine(ex.Message)

    '    End Try

    'End Sub


    'Public Sub BuildOutlookApt(ByVal cs_id, ByVal username, ByVal pwd, ByVal domain, ByVal appt_file, ByVal server)
    '    Try
    '        Dim m_xmld As System.Xml.XmlDocument
    '        Dim m_nodelist As XmlNodeList
    '        Dim m_node As XmlNode
    '        'Create the XML Document
    '        m_xmld = New System.Xml.XmlDocument()
    '        'Load the Xml file
    '        m_xmld.Load(appt_file)
    '        'Get the list of name nodes 
    '        m_nodelist = m_xmld.SelectNodes("/appointments/appt")
    '        'Loop through the nodes
    '        For Each m_node In m_nodelist
    '            Dim CS_ID_Appt = m_node.Item("cs_id").InnerXml
    '            Dim Appt_ID = m_node.Item("appt_id").InnerXml
    '            Dim Subject = m_node.Item("subject").InnerXml
    '            Dim Location = m_node.Item("location").InnerXml
    '            Dim Body = m_node.Item("body").InnerXml
    '            Dim Start_Date = m_node.Item("start").InnerXml
    '            Dim End_Date = m_node.Item("end").InnerXml

    '            If (cs_id = CS_ID_Appt) And (Convert.ToDateTime(Start_Date) > Now) Then
    '                Call CreateOutlookApptOWA(Appt_ID, Subject, Location, Body, Start_Date, End_Date, username, domain, pwd, server)
    '                Console.Write("Writing Appointment ID: " & Appt_ID & " for Cornerstone User: " & cs_id)
    '            Else
    '                Console.Write("Appointment ID: " & Appt_ID & " not associated with Cornerstone User: " & cs_id)
    '            End If
    '            Console.Write(vbCrLf)
    '        Next
    '    Catch errorVariable As Exception
    '        'Error trapping
    '        Console.Write(errorVariable.ToString())
    '    End Try

    'End Sub


    'Private Sub CreateOutlookApptOWA(ByVal Appt_ID, ByVal Subject, ByVal Location, ByVal Body, ByVal Start_Date, ByVal End_Date, ByVal username, ByVal domain, ByVal pwd, ByVal server)

    '    ' Variables
    '    Dim strExchSvrName As String
    '    Dim strMailbox As String
    '    Dim strCalendarUri As String
    '    Dim strApptItem As String
    '    Dim strDomain As String
    '    Dim strUserName As String
    '    Dim strPassword As String
    '    Dim strApptRequest As String
    '    Dim strMailInfo As String
    '    Dim strCalInfo As String
    '    Dim strXMLNSInfo As String
    '    Dim strHeaderInfo As String
    '    Dim PROPPATCHRequest As System.Net.HttpWebRequest
    '    Dim PROPPATCHResponse As System.Net.WebResponse
    '    Dim bytes() As Byte
    '    Dim PROPPATCHRequestStream As System.IO.Stream

    '    Try
    '        'ServicePointManager.ServerCertificateValidationCal lback = delegate { return true; };
    '        ' Exchange server name
    '        strExchSvrName = server

    '        ' Mailbox folder name.
    '        strMailbox = username

    '        ' Appointment item.
    '        strApptItem = "CornerStoneAppt_" & Appt_ID & ".eml"

    '        ' URI of the user's calendar folder.
    '        strCalendarUri = "https://" & strExchSvrName & "/owa/" & _
    '        strMailbox & "/Calendar/"

    '        ' User name and password of appointment creator.
    '        strUserName = username
    '        strDomain = domain
    '        strPassword = pwd

    '        Console.WriteLine(strCalendarUri)
    '        Dim xml_start_date = XmlConvert.ToString(Start_Date, XmlDateTimeSerializationMode.Local)
    '        Dim xml_end_date = XmlConvert.ToString(End_Date, XmlDateTimeSerializationMode.Local)

    '        ' XML namespace info for the WebDAV request.
    '        strXMLNSInfo = "xmlns:g=""DAV:"" " & _
    '           "xmlns:e=""http://schemas.microsoft.com/exchange/"" " & _
    '           "xmlns:mapi=""http://schemas.microsoft.com/mapi/"" " & _
    '           "xmlns:mapit=""http://schemas.microsoft.com/mapi/proptag/"" " & _
    '           "xmlns:x=""xml:"" xmlns:cal=""urn:schemas:calendar:"" " & _
    '           "xmlns:dt=""urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/"" " & _
    '           "xmlns:header=""urn:schemas:mailheader:"" " & _
    '           "xmlns:mail=""urn:schemas:httpmail:"""

    '        ' Set the appointment item properties.  The reminder time is set in seconds.
    '        ' To create an all-day meeting, set the dtstart/dtend range for 24 hours
    '        ' or more and set the alldayevent property to 1.  See the documentation
    '        ' on the properties in the urn:schemas:calendar: namespace for more information.
    '        strCalInfo = "<cal:location>" & Location & "</cal:location>" & _
    '           "<cal:dtstart dt:dt=""dateTime.tz"">" & xml_start_date & "</cal:dtstart>" & _
    '           "<cal:dtend dt:dt=""dateTime.tz"">" & xml_end_date & "</cal:dtend>" & _
    '          "<cal:instancetype dt:dt=""int"">0</cal:instancetype>" & _
    '        "<cal:busystatus>BUSY</cal:busystatus>" & _
    '        "<cal:meetingstatus>CONFIRMED</cal:meetingstatus>" & _
    '        "<cal:alldayevent dt:dt=""boolean"">0</cal:alldayevent>" & _
    '        "<cal:responserequested dt:dt=""boolean"">1</cal:responserequested>" & _
    '        "<cal:reminderoffset dt:dt=""int"">900</cal:reminderoffset>"

    '        ' Set the required attendee of the appointment.
    '        'strHeaderInfo = "<header:to>" & strMailbox & "</header:to>"

    '        ' Set the subject of the appointment.
    '        Subject = "Corner Stone Appt (" & Appt_ID & ") " & Subject
    '        strMailInfo = "<mail:subject>" & Subject & "</mail:subject>" & _
    '           "<mail:htmldescription>" & Body & "</mail:htmldescription>"

    '        ' Build the XML body of the PROPPATCH request.
    '        strApptRequest = "<?xml version=""1.0""?>" & _
    '           "<g:propertyupdate " & strXMLNSInfo & ">" & _
    '           "<g:set><g:prop>" & _
    '           "<g:contentclass>urn:content-classes:appointment</g:contentclass>" & _
    '           "<e:outlookmessageclass>IPM.Appointment</e:outlookmessageclass>" & _
    '           strMailInfo & _
    '           strCalInfo & _
    '           "<mapi:finvited dt:dt=""boolean"">1</mapi:finvited>" & _
    '           "</g:prop></g:set>" & _
    '           "</g:propertyupdate>"

    '        Dim strReusableCookies As String
    '        Net.ServicePointManager.ServerCertificateValidationCallback = AddressOf ValidateCertificate
    '        PROPPATCHRequest = CType(WebRequest.Create(New System.Uri(strCalendarUri & strApptItem)), HttpWebRequest)

    '        strReusableCookies = AuthenticateSecureOWA(strExchSvrName, strDomain, strUserName, strPassword)


    '        'AddHandler ServicePointManager.ServerCertificateValidationCallback, AddressOf ValidateCertificate

    '        ' Create the HttpWebRequest object.
    '        'PROPPATCHRequest = CType(System.Net.HttpWebRequest.Create(strCalendarUri & strApptItem),  _
    '        '                        System.Net.HttpWebRequest)

    '        PROPPATCHRequest.Headers.Add("Cookie", strReusableCookies)

    '        ' Add the network credentials to the request.
    '        'PROPPATCHRequest.Credentials = MyCredentialCache

    '        ' Specify the PROPPATCH method.
    '        PROPPATCHRequest.Method = "PROPPATCH"

    '        ' Set the content type header.
    '        PROPPATCHRequest.ContentType = "text/xml"

    '        PROPPATCHRequest.KeepAlive = True
    '        PROPPATCHRequest.AllowAutoRedirect = False

    '        ' Encode the body using UTF-8.
    '        bytes = System.Text.Encoding.UTF8.GetBytes(strApptRequest)

    '        ' Set the content header length.  This must be
    '        ' done before writing data to the request stream.
    '        PROPPATCHRequest.ContentLength = bytes.Length

    '        ' Get a reference to the request stream.
    '        PROPPATCHRequestStream = PROPPATCHRequest.GetRequestStream()

    '        ' Write the message body to the request stream.
    '        PROPPATCHRequestStream.Write(bytes, 0, bytes.Length)

    '        ' Close the Stream object to release the connection
    '        ' for further use.
    '        PROPPATCHRequestStream.Close()

    '        ' Create the appointment in the Calendar folder of the
    '        ' user's mailbox.
    '        PROPPATCHResponse = CType(PROPPATCHRequest.GetResponse(), System.Net.HttpWebResponse)

    '        Console.WriteLine("Appointment successfully created.")

    '        ' Clean up.
    '        PROPPATCHResponse.Close()

    '    Catch ex As Exception
    '        ' Catch any exceptions. Any error codes from the PROPPATCH
    '        ' or MOVE method requests on the server will be caught
    '        ' here, also.
    '        Console.WriteLine(ex.Message)

    '    End Try

    'End Sub


End Class
